# coding: utf-8

from datetime import date

from sqlalchemy.sql import text

from app.enterprise.constant import EnterpriseLevel
from app.models import BaseModel, db
from app.op.constant import ParticStatus, DemandStatus, FollowType
from app.op.models import User, Partic, Area
from app.extensions import qi_niu_proxy

# 企业账号关注地区
enterprise_to_area = db.Table(
    'enterprise_to_area',
    db.Column(
        'enterprise_id',
        db.Integer,
        db.ForeignKey('enterprises.id'),
        primary_key=True
    ),
    db.Column('area_id', db.Integer, db.ForeignKey('area.id'), primary_key=True)
)


# 企业账号子账号
enterprise_to_user = db.Table(
    'enterprise_to_user',
    db.Column(
        'enterprise_id',
        db.Integer,
        db.ForeignKey('enterprises.id'),
        primary_key=True
    ),
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True)
)


class Enterprise(BaseModel):
    """
    create by ld_wu 2018-05-08
    企业账号
    """

    __tablename__ = 'enterprises'

    search_keys = ('enterprise_name', )

    # 企业名称
    enterprise_name = db.Column(db.String(64), nullable=False)
    # 企业地址
    enterprise_address = db.Column(db.String(1024), default='', server_default='', nullable=False)
    # 企业等级
    level = db.Column(db.Integer())
    # 子账户最大数量
    account_limit = db.Column(db.Integer(), default=0)
    # 已派单数量
    dispatch_cnt = db.Column(db.Integer(), default=0)
    # 企业主id
    user_id = db.Column(db.Integer(), nullable=False)
    # 生效日期
    start_date = db.Column(db.Date())
    # 截止日期
    expired_date = db.Column(db.Date())
    # 最大派单数量
    dispatch_limit = db.Column(db.Integer(), default=0)
    # 剩余派单数量
    leave_dispatch_cnt = db.Column(db.Integer(), default=0)
    # 备注
    remark = db.Column(db.String(1024), default='', server_default='')
    # 最近派单时间
    last_dispatch_at = db.Column(db.Integer, nullable=False, server_default=text("'0'"))
    # 派单规则
    dispatch_rule = db.Column(db.Text())

    enterprise_areas = db.relationship(
        'Area',
        secondary=enterprise_to_area,
        backref=db.backref('enterprises', lazy='dynamic')
    )

    sub_accounts = db.relationship(
        'User',
        secondary=enterprise_to_user,
        backref=db.backref('enterprises', lazy='dynamic')
    )

    def __setattr__(self, key, value):
        """
        create by ld_wu 2018-05-09
        重写属性设置方法，当修改最大派单数量或者已派单数量时，
        重新计算剩余派单数量
        """
        super(Enterprise, self).__setattr__(key, value)
        if key in ('dispatch_limit', 'dispatch_cnt'):
            self.leave_dispatch_cnt = self.dispatch_limit - (self.dispatch_cnt or 0)

    @property
    def user(self):
        return User.get_by_id(self.user_id)

    @property
    def level_display(self):
        return EnterpriseLevel(self.level).display

    @property
    def partic_success_cnt(self):
        """
        create by ld_wu 2018-05-14
        企业账号抢单数（成功数量，不包含退单）
        :return:
        """
        return Partic.query.filter(
            Partic.enterprise_id == self.id,
            Partic.status == ParticStatus.SUCCEED.value,
            Partic.demand_status.in_([
                DemandStatus.DISPATCHING.value, DemandStatus.MASTER_DISPATCHING.value
            ]),
            Partic.follow_type != FollowType.GIVE_UP.value
        ).count()

    @property
    def prov_names(self):
        """
        create by ld_wu 2018-05-14
        企业账号开通省份名称
        :return:
        """
        prov_ids = {each.pid for each in self.enterprise_areas}
        provs = Area.get_list_by_ids(list(prov_ids))
        return ', '.join([each.name for each in provs])

    @property
    def valid(self):
        """
        是否仍在有效期内
        :return:
        """
        return self.expired_date >= date.today()


class SubAccountLog(BaseModel):
    """
    create by ld_wu 2018-05-09
    子账号添加或者移除的记录
    """
    __tablename__ = 'sub_account_logs'

    # 企业账号id
    enterprise_id = db.Column(db.Integer(), index=True)
    user_id = db.Column(db.Integer())
    # 操作类型(加入或者移除)
    operator_type = db.Column(db.Integer())
    # 操作人
    operator_id = db.Column(db.Integer(), default=0)
    # 操作人姓名
    operator_name = db.Column(db.String(16), default='')


# 金银牌首页的项目类型、保障体系、产品类型表，统一用'Hp'(Homepage)前缀
class HpProjectType(BaseModel):
    """
    add by zhouhl 2018-05-21
    金银牌首页的项目类型表
    """
    __tablename__ = 'hp_project_type'

    name = db.Column(db.String(64), unique=True, nullable=False)


class HpSecuritySystem(BaseModel):
    """
    add by zhouhl 2018-05-21
    金银牌首页的保障体系表
    """
    __tablename__ = 'hp_security_system'

    name = db.Column(db.String(64), unique=True, nullable=False)


class HpProductType(BaseModel):
    """
    add by zhouhl 2018-05-21
    金银牌首页的产品类型表
    """
    __tablename__ = 'hp_product_type'

    name = db.Column(db.String(64), unique=True, nullable=False)


# 企业号首页相关信息表格
class EnterpriseHomepage(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业号首页基本信息
    """
    __tablename__ = 'enterprise_homepage'

    enterprise_id = db.Column(db.Integer(), index=True)

    # TDK相关字段
    title = db.Column(db.String(1024), server_default=text("''"), default='')
    description = db.Column(db.String(1024), server_default=text("''"), default='')
    keywords = db.Column(db.String(1024), server_default=text("''"), default='')

    hostname = db.Column(db.String(256), server_default=text("''"), default='')

    # 客服名称和头像
    agent_name = db.Column(db.String(16), default='客服')
    agent_avatar = db.Column(db.String(128), default='')

    # 各模块色号
    ## 主色号
    base_color_num = db.Column(db.String(16), default='')
    ## 首屏色号
    first_screen_color_num = db.Column(db.String(16), default='#ffffff')
    ## 项目案例色号
    project_color_num = db.Column(db.String(16), default='#ffffff')
    ## 保障体系色号
    security_color_num = db.Column(db.String(16), default='#f7faff')
    ## 产品展示色号
    product_color_num = db.Column(db.String(16), default='#ffffff')
    ## 合作伙伴色号
    partner_color_num = db.Column(db.String(16), default='#f7faff')
    ## 了解我们色号
    about_us_color_num = db.Column(db.String(16), default='#ffffff')
    ## 公司规模色号
    scale_color_num = db.Column(db.String(16), default='#ffffff')

    # 页眉logo、页脚logo
    header_logo = db.Column(db.String(512), default='')
    footer_logo = db.Column(db.String(512), default='')

    # 首屏背景图、首屏标题、首屏副标题
    first_screen_background = db.Column(db.String(512), default='')
    first_screen_title = db.Column(db.String(64), default='')
    first_screen_subtitle = db.Column(db.String(64), default='')

    # 虚拟号与虚拟号图片
    virtual_number = db.Column(db.String(16), default='')
    virtual_number_img = db.Column(db.String(512), default='')

    # 项目案例副标题
    project_subtitle = db.Column(db.String(64), default='')

    # 保障体系副标题
    security_subtitle = db.Column(db.String(64), default='')

    # 产品展示副标题
    product_subtitle = db.Column(db.String(64), default='')

    # 合作伙伴副标题、合作伙伴图片
    partner_subtitle = db.Column(db.String(64), default='')
    partner_img = db.Column(db.String(512), default='')

    # 了解我们副标题
    about_us_subtitle = db.Column(db.String(64), default='')
    # 法人头像、法人姓名、注册资金、注册时间、人员规模
    legal_person_avatar = db.Column(db.String(512), default='')
    legal_person_name = db.Column(db.String(64), default='')
    registered_capital = db.Column(db.String(64), default='')
    registered_date = db.Column(db.String(64), default='')
    staff_size = db.Column(db.String(64), default='')

    # 安备和备案号
    safety_record = db.Column(db.String(128), default='')
    record_number = db.Column(db.String(128), default='')

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseHomepage.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('homepage', uselist=False),
    )

    @property
    def enterprise_name(self):
        return self.enterprise.enterprise_name

    @property
    def agent_avatar_url(self):
        return qi_niu_proxy.url(self.agent_avatar) if self.agent_avatar else ''

    @property
    def header_logo_url(self):
        return qi_niu_proxy.url(self.header_logo) if self.header_logo else ''

    @property
    def footer_logo_url(self):
        return qi_niu_proxy.url(self.footer_logo) if self.footer_logo else ''

    @property
    def first_screen_background_url(self):
        return qi_niu_proxy.url(self.first_screen_background) if self.first_screen_background else ''

    @property
    def partner_img_url(self):
        return qi_niu_proxy.url(self.partner_img) if self.partner_img else ''

    @property
    def legal_person_avatar_url(self):
        return qi_niu_proxy.url(self.legal_person_avatar) if self.legal_person_avatar else ''

    @property
    def virtual_number_img_url(self):
        return qi_niu_proxy.url(self.virtual_number_img) if self.virtual_number_img else ''


class EnterpriseProject(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业项目表
    """
    __tablename__ = 'enterprise_project'

    enterprise_id = db.Column(db.Integer(), index=True)
    # 项目类型
    project_type_id = db.Column(db.Integer())
    # 项目图片
    project_img = db.Column(db.String(512))
    # 造价
    project_cost = db.Column(db.String(64))
    # 项目标题
    project_title = db.Column(db.String(128))
    # 项目内容
    project_text = db.Column(db.String(128))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    project_type = db.relationship(
        'HpProjectType',
        primaryjoin='foreign(EnterpriseProject.project_type_id) == remote(HpProjectType.id)',
        single_parent=True,
    )

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseProject.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('projects', order_by='EnterpriseProject.weight'),
    )

    @property
    def project_type_display(self):
        return self.project_type.name if self.project_type else '--'

    @property
    def project_img_url(self):
        return qi_niu_proxy.url(self.project_img) if self.project_img else ''


class EnterpriseSecurity(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业保障体系表
    """
    __tablename__ = 'enterprise_security'

    enterprise_id = db.Column(db.Integer(), index=True)
    # 保障体系ID
    security_id = db.Column(db.Integer())
    security_text = db.Column(db.String(512))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseSecurity.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('securities', order_by='EnterpriseSecurity.weight'),
    )

    security_system = db.relationship(
        'HpSecuritySystem',
        primaryjoin='foreign(EnterpriseSecurity.security_id) == remote(HpSecuritySystem.id)',
        single_parent=True,
    )

    @property
    def security_display(self):
        return self.security_system.name if self.security_system else '--'


class EnterpriseProduct(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业产品表
    """
    __tablename__ = 'enterprise_product'

    enterprise_id = db.Column(db.Integer(), index=True)
    # 产品类型ID
    product_type_id = db.Column(db.Integer())
    product_img = db.Column(db.String(512))
    product_title = db.Column(db.String(64))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseProduct.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('products', order_by='EnterpriseProduct.weight'),
    )

    product_type = db.relationship(
        'HpProductType',
        primaryjoin='foreign(EnterpriseProduct.product_type_id) == remote(HpProductType.id)',
        single_parent=True,
    )

    @property
    def product_type_display(self):
        return self.product_type.name if self.product_type else '--'

    @property
    def product_img_url(self):
        return qi_niu_proxy.url(self.product_img) if self.product_img else ''


class EnterpriseMediaReport(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业媒体报道表
    """
    __tablename__ = 'enterprise_media_report'

    enterprise_id = db.Column(db.Integer(), index=True)
    report_img = db.Column(db.String(512))
    report_title = db.Column(db.String(128))
    report_text = db.Column(db.String(512))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseMediaReport.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('media_reports', order_by='EnterpriseMediaReport.weight'),
    )

    @property
    def report_img_url(self):
        return qi_niu_proxy.url(self.report_img) if self.report_img else ''


class EnterprisePicture(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业公司图片表
    """
    __tablename__ = 'enterprise_picture'

    enterprise_id = db.Column(db.Integer(), index=True)
    picture_img = db.Column(db.String(512))
    picture_title = db.Column(db.String(128))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterprisePicture.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('pictures', order_by='EnterprisePicture.weight'),
    )

    @property
    def picture_img_url(self):
        return qi_niu_proxy.url(self.picture_img) if self.picture_img else ''


class EnterpriseHonour(BaseModel):
    """
    add by zhouhl 2018-05-21
    企业荣誉资质表
    """
    __tablename__ = 'enterprise_honour'

    enterprise_id = db.Column(db.Integer(), index=True)
    honour_img = db.Column(db.String(512))
    honour_title = db.Column(db.String(128))
    weight = db.Column(db.Integer(), server_default=text("'0'"), default=0)

    enterprise = db.relationship(
        'Enterprise',
        primaryjoin='foreign(EnterpriseHonour.enterprise_id) == remote(Enterprise.id)',
        single_parent=True,
        backref=db.backref('honours', order_by='EnterpriseHonour.weight'),
    )

    @property
    def honour_img_url(self):
        return qi_niu_proxy.url(self.honour_img) if self.honour_img else ''
